package mysql

import (
	"gorm.io/gorm"
	"novel-start/novelrpc/novelrpc"
)

type Novel struct {
	gorm.Model
	Title     string `gorm:"type:varchar(50);not null"`
	Type      string `gorm:"type:varchar(50);not null"`
	NovelDesc string `gorm:"type:varchar(50);not null"`
	UserId    int64  `gorm:"type:int(11);not null"`
	NovelUrl  string `gorm:"type:varchar(500);not null"`
	NovelNum  string `gorm:"type:varchar(50);not null"`
}

func (n *Novel) NovelAdd(db *gorm.DB) error {
	return db.Debug().Create(n).Error
}

func (n *Novel) NovelShow(db *gorm.DB, in *novelrpc.NovelShowRequest) novelrpc.NovelShowResponse {
	var novelShow novelrpc.NovelShowResponse
	tx := db.Debug().Model(&Novel{}).
		Select("novels.id as novel_id,novels.*,nick_name,head_image").
		Joins("left join users on users.id = novels.user_id").
		Where("novels.user_id = ?", in.UserId)
	if in.Key != "" {
		tx.Where("title like ? or type like ? or novel_desc like ?", "%"+in.Key+"%", "%"+in.Key+"%", "%"+in.Key+"%")
	}
	tx.First(&novelShow)
	return novelShow
}

func (n *Novel) FindNovelById(db *gorm.DB, id int64) error {
	return db.Debug().Where("id = ?", id).First(n).Error
}

func NovelList(db *gorm.DB, in *novelrpc.NovelListRequest, list []*novelrpc.NovelList) []*novelrpc.NovelList {
	db.Debug().Model(&Novel{}).
		Select("novels.id as novel_id,novels.*,nick_name,head_image").
		Joins("left join users on users.id = novels.user_id").
		Where("novels.user_id = ?", in.UserId).
		Scopes(Paginate(int(in.Page), int(in.PageSize))).Find(&list)
	return list
}
